package com.faxsun.admin.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.broadleafcommerce.core.catalog.dao.ProductDao;
import org.broadleafcommerce.core.catalog.domain.Product;
import org.broadleafcommerce.core.order.domain.OrderItemAttribute;
import org.broadleafcommerce.openadmin.web.controller.AdminAbstractController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.faxsun.admin.service.TreasureService;
import com.faxsun.admin.web.domain.form.GenerateWinnerForm;
import com.faxsun.core.order.dao.FSOrderItemDao;

@Controller
@RequestMapping("/" + TreasureAdminController.SECTION_KEY)
public class TreasureAdminController extends AdminAbstractController {

	private static final Logger LOG = Logger.getLogger(TreasureAdminController.class);

	protected static final String SECTION_KEY = "treasure";

	@Resource(name = "treasuerService")
	protected TreasureService treasureService;

	@Resource(name = "blProductDao")
	protected ProductDao productDao;

	@Resource(name = "blOrderItemDao")
	FSOrderItemDao fsOrderItemDao;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String listToBeDraw(HttpServletRequest request, HttpServletResponse response, Model model)
			throws Exception {

		List<Product> products = treasureService.list();
		model.addAttribute("products", products);

		model.addAttribute("viewType", "list");
		setModelAttributes(model, SECTION_KEY);
		return "/treasure/default";
	}

	@RequestMapping(value = "/generate", method = RequestMethod.GET)
	public String generateWinner(HttpServletRequest request, HttpServletResponse response, Model model,
			@ModelAttribute("generateWinnerForm") GenerateWinnerForm generateWinnerForm) throws Exception {

		String productId = request.getParameter("productId");
		generateWinnerForm.setProductId(productId);

		model.addAttribute("viewType", "generate");
		setModelAttributes(model, SECTION_KEY);
		return "/treasure/default";
	}

	@RequestMapping(value = "/generate", method = RequestMethod.POST)
	public String generateWinnerPost(HttpServletRequest request, HttpServletResponse response, Model model,
			@ModelAttribute("generateWinnerForm") GenerateWinnerForm generateWinnerForm) throws Exception {

		String number = generateWinnerForm.getNumber();
		String productId = generateWinnerForm.getProductId();

		if (number == null || number.isEmpty() || productId == null || productId.isEmpty()) {
			model.addAttribute("viewType", "generate");
			setModelAttributes(model, SECTION_KEY);
			return "/treasure/default";
		}
		try {
			Product product = productDao.readProductById(new Long(generateWinnerForm.getProductId()));
			List<OrderItemAttribute> orderItemAttributes = fsOrderItemDao
					.readAllOrderItemAttributesBySku(product.getDefaultSku());
			
			/*
			 * If were going to generate the winning number by the treasure customer count, 
			 * pass in the orderItemAttr size as range for generateWinningNumberForProduct()
			 */
			// Long winningNumber = treasureService.generateWinningNumberForProduct(product, new Long(
			// 		generateWinnerForm.getNumber()), orderItemAttributes.size());
			
			/*
			 * Otherwise do not pass in the range parameter 
			 */
			Long winningNumber = treasureService.generateWinningNumberForProduct(product, new Long(
					generateWinnerForm.getNumber()));
			
			if (winningNumber.longValue() != 0) {
				treasureService.setWinningNumberForProduct(product, winningNumber);
				treasureService.findAndSaveTreasureWinnerByProduct(product, orderItemAttributes);
			}

		} catch (NumberFormatException nfe) {
			LOG.error("product id or seed number is not number!!! ", nfe);
			model.addAttribute("viewType", "generate");
			setModelAttributes(model, SECTION_KEY);
			return "/treasure/default";
		} catch (Exception e) {
			LOG.error("Error occurs! ", e);
			model.addAttribute("viewType", "generate");
			setModelAttributes(model, SECTION_KEY);
			return "/treasure/default";
		}
		return "redirect:/treasure/list";
	}

	@ModelAttribute("generateWinnerForm")
	public GenerateWinnerForm initGenerateWinnerForm() {
		GenerateWinnerForm generateWinnerForm = new GenerateWinnerForm();
		return generateWinnerForm;
	}
}